﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Drawing.Drawing2D;
using HZH_Controls;
using System.Threading;
using HZH_Controls.Forms;
using System.Security.Cryptography;

namespace 渐变
{
    public partial class UserLogin : Form
    {

/*            <add key = "connstring" value="Data Source=LAPTOP-D9SO7O4T\SQLEXPRESS;Initial Catalog=CarRental;Integrated Security=TRUE" />
*/
        /// <summary>
        /// 设置窗体的Region
        /// </summary>
        public void SetWindowRegion()
        {
            GraphicsPath FormPath;
            Rectangle rect = new Rectangle(0, 0, this.Width, this.Height);
            FormPath = GetRoundedRectPath(rect, 50);
            this.Region = new Region(FormPath);

        }
        /// <summary>
        /// 绘制圆角路径
        /// </summary>
        /// <param name="rect"></param>
        /// <param name="radius"></param>
        /// <returns></returns>
        private GraphicsPath GetRoundedRectPath(Rectangle rect, int radius)
        {
            int diameter = radius;
            Rectangle arcRect = new Rectangle(rect.Location, new Size(diameter, diameter));
            GraphicsPath path = new GraphicsPath();

            // 左上角
            path.AddArc(arcRect, 180, 90);

            // 右上角
            arcRect.X = rect.Right - diameter;
            path.AddArc(arcRect, 270, 90);

            // 右下角
            arcRect.Y = rect.Bottom - diameter;
            path.AddArc(arcRect, 0, 90);

            // 左下角
            arcRect.X = rect.Left;
            path.AddArc(arcRect, 90, 90);
            path.CloseFigure();//闭合曲线
            return path;
        }

        public UserLogin()
        {

            InitializeComponent();
        }
        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case 0x84:
                    base.WndProc(ref m);
                    if ((int)m.Result == 0x1)
                        m.Result = (IntPtr)0x2;
                    return;
            }

            base.WndProc(ref m);
        }

      

        private void UserLogin_Load(object sender, EventArgs e)
        {
            slideA.Left = 49;  //这个数值要自己调整
            slideB.Left = 49;  //这个数值要自己调整
            slideB.Visible = false;
            SetWindowRegion();

        }

        private void btnSignUp_Click(object sender, EventArgs e)
        {
            slideB.Visible = false;
            slideA.Visible = true;
            slideA.Refresh();
        }

        private void btnSignIn_Click(object sender, EventArgs e)
        {
            slideA.Visible = false;
            slideB.Visible = true;
            slideB.Refresh();
        }

        public static string PasswordEncryption(string pwd)
        {
            //创建SHA1加密算法对象
            SHA1 sha1 = SHA1.Create();
            //将原始密码转换为字节数组
            byte[] originalPwd = Encoding.UTF8.GetBytes(pwd);
            //执行加密
            byte[] encryPwd = sha1.ComputeHash(originalPwd);
            //将加密后的字节数组转换为大写字符串
            return string.Join("", encryPwd.Select(b => string.Format("{0:x2}",
          b)).ToArray()).ToUpper();
        }

        public static string HmacSHA256(byte[] key,byte[] content)
        {
            var sign = string.Empty;
            using(var hmacsha256  = new System.Security.Cryptography.HMACSHA256(key))
            {
                byte[] hashmessage = hmacsha256.ComputeHash(content);
                if(hashmessage != null && hashmessage.Length > 0)
                {
                    foreach(var item in hashmessage)
                    {
                        sign += item.ToString("X");
                    }
                }
            }
            return sign;
        }


        private void btnLogin_Click(object sender, EventArgs e)
        {
            /*string uneText = this.txtLoginName.Text.Trim();
            string pwdText = this.txtLoginPwd.Text.Trim();*/
            Computer computer = new Computer();
            if (user.Checked)
            {
                //根据用户名查找员工信息
                string sql = "select * from uUser where uUsername = @uUsername";
                SqlParameter p = new SqlParameter("@uUsername", txtLoginName.Text);
                DataTable dt = new DataTable();
                dt = DBHelper.ExecuteQuery(sql, p);
                if (dt.Rows.Count > 0)
                {
                    userInfo userInfo = new userInfo();
                    userInfo.uId = Convert.ToInt32(dt.Rows[0][0]);
                    userInfo.uUsername = dt.Rows[0][1].ToString();
                    userInfo.uPassword = dt.Rows[0][2].ToString();
                    userInfo.uPhone = dt.Rows[0][3].ToString();
                    userInfo.uAddress = dt.Rows[0][4].ToString();

                    //用户名存在验证密码
                    if (txtLoginPwd.Text == dt.Rows[0][2].ToString())
                    {
                        //密码正确
                        this.ShowSuccessTip("登录成功！");
                        //添加登陆者的信息到数据库
                        string sqlLog = "insert into logTable (logName,logTime,logIp,logPermission) values (@logName,@logTime,@logIp,@logPermission)";
                        SqlParameter[] logPs =
                        {                         
                            new SqlParameter("@logName",txtLoginName.Text),
                            new SqlParameter("@logTime",DateTime.Now),
                            new SqlParameter("@logIp",computer.IpAddress),
                            new SqlParameter("@logPermission","普通用户")
                    };
                        DBHelper.ExecuteNonQuery(sqlLog, logPs);
                        userMain userMain = new userMain();
                        userMain.Tag = userInfo;
                        userMain.Show();
                        this.Hide();
                    }
                    else
                    {

                        this.ShowErrorDialog("密码错误");
                        txtLoginName.Text = "";
                        txtLoginPwd.Text = "";
                    }
                }
                else
                {
                    this.ShowErrorDialog("用户名不存在");
                    txtLoginName.Text = "";
                    txtLoginPwd.Text = "";
                }
            }
            
            else if (admin.Checked)
            {
                //根据用户名查找管理员信息
                string sql = "select * from Admin where superName = @superName";
                SqlParameter p = new SqlParameter("@superName", txtLoginName.Text);
                DataTable dt = new DataTable();
                dt = DBHelper.ExecuteQuery(sql, p);
                if (dt.Rows.Count > 0)
                {
                    Admin admin = new Admin();
                    admin.superName = dt.Rows[0][0].ToString();
                    admin.superPassword = dt.Rows[0][1].ToString();
                    //用户名存在验证密码
                    if (txtLoginPwd.Text == admin.superPassword)
                    {
                        ControlHelper.ThreadRunExt(this, () =>
                        {
                            Thread.Sleep(500);
                            ControlHelper.ThreadInvokerControl(this, () =>
                            {      
                                //添加登陆者的信息到数据库
                                string sqlLog = "insert into logTable (logName,logTime,logIp,logPermission) values (@logName,@logTime,@logIp,@logPermission)";
                                SqlParameter[] logPs =
                                {
                            new SqlParameter("@logName",txtLoginName.Text),
                            new SqlParameter("@logTime",DateTime.Now),
                            new SqlParameter("@logIp",computer.IpAddress),
                            new SqlParameter("@logPermission","超级管理员")
                    };
                                DBHelper.ExecuteNonQuery(sqlLog, logPs);
                                this.ShowSuccessTip("管理员账号登录成功！");
                                Form1 f1 = new Form1();
                                f1.Tag = admin;

                                f1.Show();
                                this.Hide();
                            });
                        }, null, this);

                        
                    }
                    else
                    {
                        this.ShowErrorDialog("管理员密码错误");
                        txtLoginName.Text = "";
                        txtLoginPwd.Text = "";
                    }
                }
                else
                {
                    this.ShowErrorDialog("此管理员不存在");
                    txtLoginName.Text = "";
                    txtLoginPwd.Text = "";
                }
            }
            else
            {
                this.ShowErrorDialog("请选择登录类型");
            }




        }
        public void clearMsg()
        {
            txtRegName.Text = "";
            txtRegPhone.Text = "";
            txtRegPwd.Text = "";
            txtRegAddress.Text = "";
        }

        //注册按钮
        private void txtReg_Click(object sender, EventArgs e)
        {
            //检查数据库是否已存在该用户
            string sql2 = "select * from uUser where uUsername = @uUsername";
            SqlParameter p = new SqlParameter("@uUsername", txtRegName.Text);
            DataTable dt = new DataTable();
            dt = DBHelper.ExecuteQuery(sql2, p);
            if (dt.Rows.Count > 0)
            {
                //已存在该用户
                this.ShowErrorTip("用户名已存在！请重新注册！");
            }
            else
            {
                //用户注册
                string sql = "insert into uUser(uUsername,uPassword,uPhone,uAddress) values(@uUsername,@uPassword,@uPhone,@uAddress)";
                SqlParameter[] ps =
               {
               new SqlParameter("@uUsername",txtRegName.Text),
                new SqlParameter("@uPassword",txtRegPhone.Text),
                new SqlParameter("@uPhone",txtRegPwd.Text),
                new SqlParameter("@uAddress",txtRegAddress.Text)
        };

                int fin = DBHelper.ExecuteNonQuery(sql, ps);
                if (fin > 0)
                {
                    this.ShowSuccessTip("注册成功");
                    clearMsg();
                }
                else
                {
                    this.ShowErrorTip("注册失败");
                }
            }
        }

        /*对注册的用户名进行检测*/
        private void txtRegName_KeyUp(object sender, KeyEventArgs e)
       {
            // 检查数据库是否已存在该用户
            string sql2 = "select * from uUser where uUsername = @uUsername";
            SqlParameter p = new SqlParameter("@uUsername", txtRegName.Text);
            DataTable dt = new DataTable();
            dt = DBHelper.ExecuteQuery(sql2, p);
            if (dt.Rows.Count > 0)
            {
                //已存在该用户
                nameTip.Text = "用户名已存在";
                nameTip.ForeColor = System.Drawing.Color.Red;
            }
            else
            {
                nameTip.Text = "可使用";
                nameTip.ForeColor = System.Drawing.Color.Green;
            }
        }

        private void bunifuCustomLabel1_Click(object sender, EventArgs e)
        {

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnMin_Click(object sender, EventArgs e)
        {
            WindowState = FormWindowState.Minimized;
        }
    }
}
